package com.qianhui.dao;

import com.qianhui.common.CM;
import com.qianhui.common.IResult;
import com.qianhui.pojo.Advertisement;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * A data access object (DAO) providing persistence and search support for
 * Advertisement entities. Transaction control of the save(), update() and
 * delete() operations can directly support Spring container-managed
 * transactions or they can be augmented to handle user-managed Spring
 * transactions. Each of these methods provides additional information for how
 * to configure it for the desired type of transaction control.
 *
 * @author MyEclipse Persistence Tools
 * @see com.qianhui.pojo.Advertisement
 */
public class AdvertisementDAO extends BaseHibernateDAO
{
    private static final Logger log = LoggerFactory.getLogger(AdvertisementDAO.class);
    // property constants
    public static final String ADVERTISEMENT_PICTURE = "advertisementPicture";
    public static final String ADVERTISEMENT_LINK = "advertisementLink";
    public static final String ADVERTISEMENT_TITLE = "advertisementTitle";
    public static final String ADVERTISEMENT_TYPE = "advertisementType";
    public static final String USER_ID = "userId";

    public Advertisement save(Advertisement transientInstance)
    {
        Transaction tx = null;
        try
        {
            tx = getSession().beginTransaction();
            getSession().saveOrUpdate(transientInstance);
            tx.commit();
        } catch (HibernateException e)
        {
            e.printStackTrace();
            if (tx != null)
            {
                tx.rollback();
            }
            return null;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
        return transientInstance;
    }

    public List<Advertisement> saveList(List<Advertisement> list)
    {
        Transaction tx = null;
        try
        {
            tx = getSession().beginTransaction();
            for (Advertisement listRecord : list)
            {
                getSession().saveOrUpdate(listRecord);
            }
            tx.commit();
        } catch (HibernateException e)
        {
            e.printStackTrace();
            if (tx != null)
            {
                tx.rollback();
            }
            return null;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
        return list;
    }

    public int delete(Advertisement persistentInstance)
    {
        Transaction tx = null;
        try
        {
            tx = getSession().beginTransaction();
            getSession().delete(persistentInstance);
            tx.commit();
        } catch (HibernateException e)
        {
            e.printStackTrace();
            if (tx != null)
            {
                tx.rollback();
            }
            return IResult.DELETE_EXCEPTION;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
        return IResult.DELETE_SUCCESS;
    }


    public int deleteByIdList(List<String> idList)
    {
        Transaction tx = null;
        try
        {
            tx = getSession().beginTransaction();
            String sql = "delete Advertisement a where a.advertisementId in (:idList)";
            Query query = getSession().createQuery(sql);
            query.setParameterList("idList", idList);
            query.executeUpdate();
            tx.commit();
        } catch (HibernateException e)
        {
            e.printStackTrace();
            if (tx != null)
            {
                tx.rollback();
            }
            return IResult.DELETE_EXCEPTION;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
        return IResult.DELETE_SUCCESS;
    }


    public Advertisement findById(java.lang.String id)
    {
        log.debug("getting Advertisement instance with id: " + id);
        try
        {
            Advertisement instance = (Advertisement) getSession().get("com.qianhui.pojo.Advertisement", id);
            return instance;
        } catch (HibernateException e)
        {
            e.printStackTrace();
            return null;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
    }


    public List findByIdList(List<String> idList)
    {
        try
        {
            String queryString = "from Advertisement as model where model.advertisementId in (:idList)";
            Query queryObject = getSession().createQuery(queryString);
            queryObject.setParameterList("idList", idList);
            return queryObject.list();
        } catch (HibernateException e)
        {
            e.printStackTrace();
            return null;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
    }


    public List findByProperty(String propertyName, Object value)
    {
        log.debug("finding Advertisement instance with property: " + propertyName + ", value: " + value);
        try
        {
            String queryString = "from Advertisement as model where model." + propertyName + "= ?";
            Query queryObject = getSession().createQuery(queryString);
            queryObject.setParameter(0, value);
            return queryObject.list();
        } catch (HibernateException e)
        {
            e.printStackTrace();
            return null;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
    }

    public List findByAdvertisementPicture(Object advertisementPicture)
    {
        return findByProperty(ADVERTISEMENT_PICTURE, advertisementPicture);
    }

    public List findByAdvertisementLink(Object advertisementLink)
    {
        return findByProperty(ADVERTISEMENT_LINK, advertisementLink);
    }

    public List findByAdvertisementTitle(Object advertisementTitle)
    {
        return findByProperty(ADVERTISEMENT_TITLE, advertisementTitle);
    }

    public List findByAdvertisementType(Object advertisementType)
    {
        return findByProperty(ADVERTISEMENT_TYPE, advertisementType);
    }

    public List findByUserId(Object userId)
    {
        return findByProperty(USER_ID, userId);
    }

    public List findAll()
    {
        log.debug("finding all Advertisement instances");
        try
        {
            String queryString = "from Advertisement";
            Query queryObject = getSession().createQuery(queryString);
            return queryObject.list();
        } catch (HibernateException e)
        {
            e.printStackTrace();
            return null;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
    }


    public List getListByIndexAndPageSizeAnd_type_userId(int index, int pageSize, String type, String userId)
    {
        try
        {
            String sql = "from Advertisement a where a.advertisementType=:type :idSql order by a.advertisementUpdateTime desc";
            if (CM.validIsEmpty(userId) == true)
            {
                sql = sql.replace(":idSql", " ");
            }
            else
            {
                sql = sql.replace(":idSql", " and a.userId=:userId ");
            }
            Query query = getSession().createQuery(sql);

            query.setParameter("type", type);
            if (CM.validIsEmpty(userId) == false)
            {
                query.setParameter("userId", userId);
            }
            query.setFirstResult((index - 1) * pageSize);
            query.setMaxResults(pageSize);
            List tempList = query.list();
            if (tempList == null)
            {
                return null;
            }
            else
            {
                if (tempList.size() > 0)
                {
                    return tempList;
                }
                else
                {
                    return null;
                }
            }
        } catch (HibernateException e)
        {
            e.printStackTrace();
            return null;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
    }

    public int getTotalCountBy_type_userId(String type, String userId)
    {
        try
        {
            String sql = "select count(*) from Advertisement a where a.advertisementType=:type :idSql order by a.advertisementUpdateTime desc";
            if (CM.validIsEmpty(userId) == true)
            {
                sql = sql.replace(":idSql", " ");
            }
            else
            {
                sql = sql.replace(":idSql", " and a.userId=:userId ");
            }
            Query query = getSession().createQuery(sql);

            query.setParameter("type", type);
            if (CM.validIsEmpty(userId) == false)
            {
                query.setParameter("userId", userId);
            }
            int num = ((Number) query.iterate().next()).intValue();
            return num;
        } catch (HibernateException e)
        {
            e.printStackTrace();
            return -1;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
    }
}